#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author   : Moty
# @Time     : 2024/1/22 0:09
# @File     : kc16_13.py
# @Project  : jt808
def parse_13_Upload_Realtime_Monitoring_Data(body):
    # 解析0x8003 补传分包请求
    data = {
        "交易流水号": body[0:32],
        "桩编号": body[32:46],
        "枪号": f"{int(body[46:48], 16)}枪({body[46:48]})",
        "状态": f"{status(body[48:50])}({body[48:50]})",
        "枪是否归位": f"{whether_reset(body[50:52])}({body[50:52]})",
        "是否插枪": f"{whether_insert_gun(body[52:54])}({body[52:54]})",
        "输出电压": f"{standby_calc(body[54:58],10)}({body[54:58]})",
        "输出电流": f"{standby_calc(body[58:62],10)}({body[58:62]})",
        "枪线温度": f"{int(body[62:64], 16)-50}℃({body[62:64]})",
        "枪线编码": f"{body[64:80]}({body[64:80]})",
        "SOC": f"{body[80:82]}({body[80:82]})",
        "电池组最高温度": f"{int(body[82:84], 16)-50}℃({body[82:84]})",
        "累计充电时间": f"{int(body[84:88], 16)}分({body[84:88]})",
        "剩余时间": f"{int(body[88:92], 16)}分({body[88:92]})",
        "充电度数": f"{standby_calc(body[92:100],10000)}度({body[92:100]})",
        "计损充电度数": f"{standby_calc(body[100:108],10000)}度({body[100:108]})",
        "已充金额": f"{standby_calc(body[108:116],10000)}元({body[108:116]})",
        "硬件故障": parse_hardware_faults(body[116:120]),
    }
    formatted_data = ""
    for key, value in data.items():
        formatted_data += f"{key}: {value}\n"
    return formatted_data


def status(statu):
    return "离线" if statu == "00" else "故障" if statu == "01" else "空闲" if statu == "02" else "充电" if statu == "03" \
        else "未知结果"


def whether_reset(s):
    return "否" if s == "00" else "是" if s == "01" else "未知" if s == "02" else "非法数据"


def whether_insert_gun(s):
    return "否" if s == "00" else "是" if s == "01" else "非法数据"


def standby_calc(s, rate):
    # 如果等于0则返回"待机 0"，其他则返回值
    return "待机 0" if int(s, 16) == 0 else int(s, 16)/rate


def parse_hardware_faults(hex_str):
    bin_code = format(int(hex_str, 16), '016b')
    if len(bin_code) != 16 or not set(bin_code).issubset({'0', '1'}):
        raise ValueError("输入必须是一个16位的二进制字符串")

    faults = {
        "急停按钮动作故障": bin_code[0] == '1',
        "无可用整流模块": bin_code[1] == '1',
        "出风口温度过高": bin_code[2] == '1',
        "交流防雷故障": bin_code[3] == '1',
        "交直流模块DC20通信中断": bin_code[4] == '1',
        "绝缘检测模块FC08通信中断": bin_code[5] == '1',
        "电度表通信中断": bin_code[6] == '1',
        "读卡器通信中断": bin_code[7] == '1',
        "RC10通信中断": bin_code[8] == '1',
        "风扇调速板故障": bin_code[9] == '1',
        "直流熔断器故障": bin_code[10] == '1',
        "高压接触器故障": bin_code[11] == '1',
        "门打开": bin_code[12] == '1'
    }
    # 生成故障信息的字符串表示
    fault_messages = " ".join([f"{fault}({'是 1' if status else '否 0'})" for fault, status in faults.items()])
    # 将故障信息的字符串表示添加到返回的字典中
    faults["故障信息"] = fault_messages
    return faults["故障信息"]


__all__ = ['parse_13_Upload_Realtime_Monitoring_Data']
